package nl.science.uva.pico.operator;

import nl.science.uva.pico.Stack;
import nl.science.uva.pico.operand.Operand;

/** 
 * Div divides 2 Integer variables. 
 * 
 * @author Ivo van Dongen, Karel Pieterson
 * @version 1.0
 */
public class Div extends Operator {

	public Div(Stack stack) {
		super(stack, null, null);
	}

    /** 
     * Div: This instruction calculates x1/x2, respectively for integer 
     * constants x1 and x2 at the top of the stack.
     * 
     * <p>Divide pops 2 values from the top of the stack as Integers, divides pop 1 by pop 2 and pushes the resulting
     * value back on the stack
     *  
     * @throws IllegalStateException 
     *  
     */
	@Override
	public void perform() {
		Integer[] operands = new Integer[2];
		
		//Check number of operands
		if(getStack().size() >= 2) {
			operands[0] = getStack().pop().getIntegerValue();
			operands[1] = getStack().pop().getIntegerValue();
			
			//Divide by zero?
			if(operands[1] == 0) {
				throw new IllegalArgumentException("Divide by zero");
			}
			
			Integer result = operands[0] / operands[1];
			getStack().push(new Operand(result));
			
		} else {
			throw new IllegalStateException(" Too few operands, Div needs 2 operands");
		}
	}

}
